<?php

namespace Our;

/**
 * 控制器抽象类
 */
abstract class Controller_Abstract extends \Yaf\Controller_Abstract {

    /**
     * 根据版本号参数v创建业务层对象
     * 
     * @param $businessName 业务层名称
     * @return object
     */
    protected function _createBusinessObject($businessName) {
        $v = $this->getRequest()->getParam('v');
        if (empty($v)) {
            eval('$business = \Business\\' . ucfirst($businessName) . 'Model::getInstance();');
        } else {
            if (!class_exists('\Business\V' . $v . '\\' . ucfirst($businessName) . 'Model')) {
                eval('$business = \Business\\' . ucfirst($businessName) . 'Model::getInstance();');
            } else {
                eval('$business = \Business\V' . $v . '\\' . ucfirst($businessName) . 'Model::getInstance();');
            }
        }

        return $business;
    }

    /**
     * 获取post的参数
     * 
     * @param string $key
     * @param mix $defaultValue
     * @return mix
     */
    protected function _getPost($key = null, $defaultValue = null) {
        if (!$key) {
            return $_POST;
        }

        $value = $this->getRequest()->getPost($key);
        if (!$value) {
            $value = isset($_POST[$key]) ? $_POST[$key] : null;
        }
        if (!$value) {
            $value = $defaultValue;
        }
        return $value;
    }

    /**
     * 获取cookie的值
     * 
     * @param string $key
     * @param mix $default
     */
    public function getCookie($key, $default = null) {
        if (isset($_COOKIE[$key]) && strlen($_COOKIE[$key]) > 0)
            return $_COOKIE[$key];
        return $default;
    }

    /**
     * 输出错误的信息
     * 
     * @param string $message
     * @param int $errno 错误编号
     */
    protected function _echoErrorMessage($message, $errno = 1) {
        //data输出为空对象
        $data = (object) array();

        $return = array(
            'errno'  => $errno . '',
            'errmsg' => $message,
            'data'   => $data
        );
        if ($this->getRequest()->getQuery('is_jsonp')) {
            $callback = $this->getRequest()->getQuery('callback');
            if ($callback) {
                $this->getResponse()->setBody($callback . "(" . json_encode($return) . ")");
            }
        } else {
            $this->_displayJson($return);
        }
    }

    /**
     * 请求时输出成功的信息,并退出
     * 
     * @param string $message
     * @param array $data
     */
    protected function _echoSuccessMessage($message, $data = array(), $is_array = false) {
        //检测fields字段，如果有设置则只传输相应的字段值
        $fields = array_filter(explode(',', $this->getRequest()->getParam('fields')));
        if ($fields) {
            foreach ($data as $k => $v) {
                if (!in_array($k, $fields)) {
                    unset($data[$k]);
                }
            }
        }

        //如果data为空则转成空对象格式输出
        if (!$data && !$is_array) {
            $data = (object) array();
        }

        $return = array(
            'errno'  => '0',
            'errmsg' => $message,
            'data'   => $data
        );

        //检测是否有jsonp的
        if ($this->getRequest()->getQuery('is_jsonp')) {
            $callback = $this->getRequest()->getQuery('callback');
            if ($callback) {
                $this->getResponse()->setBody($callback . "(" . json_encode($return) . ")");
            }
        } else {
            $this->_displayJson($return);
        }
    }

    /**
     * 输出json格式的数据
     * 
     * @param mixed $data
     */
    public function _displayJson($data) {
        if (!$this->getRequest()->isCli()) {
            header('Content-Type: application/json; charset=utf-8');
        }
        $this->getResponse()->setBody(json_encode($data));
    }

    /**
     * 校验是否登录
     * 
     * @return int 登录的会员编号
     * @throws \Exception
     */
    public function _validLogin() {
        $sso = $this->_getSso();
        if (!$sso) {
            \Error\ErrorModel::throwException(100013);
        }
        //这里要解析获取用户编号
        $http   = \Http\User\UserModel::getInstance();
        $result = $http->analyzeSso($sso);
        if (!$result) {
            \Error\ErrorModel::throwException(110020);
        }

        $uid = isset($result["uid"]) ? $result["uid"] : 0;
        if (!$uid) {
            \Error\ErrorModel::throwException(100013);
        }

        //同步本地用户扩展
        try {
            $business = \Business\User\UserModel::getInstance();
            $business->syncLocalUserExt($uid);
        } catch (Exception $ex) {
            
        }

        return $uid;
    }

    /**
     * 检查是否登录(不提示错误信息)
     * 
     * @return int
     */
    public function _checkIsLogin() {
        $sso = $this->_getSso();
        if (!$sso) {
            return 0;
        }
        //这里要解析获取用户编号
        $http   = \Http\User\UserModel::getInstance();
        $result = $http->analyzeSso($sso);
        if (!$result) {
            return 0;
        }

        $uid = isset($result["uid"]) ? $result["uid"] : 0;
        if (!$uid) {
            return 0;
        }
        return $uid;
    }

    /**
     * 获取登录cookie
     * 
     * @return string
     */
    public function _getSso() {
        $sso = $this->getCookie("sso");
        if (!$sso) {
            $sso = empty($_REQUEST["sso"]) ? "" : $_REQUEST["sso"];
        }
        if (!$sso) {
            $sso = empty($_SERVER["HTTP_SSO"]) ? "" : $_SERVER["HTTP_SSO"];
        }
        return $sso;
    }

    /**
     * 获取平台
     * 
     * @return string
     */
    public function _getPlatform() {
        //http header
        if (!empty($_SERVER["HTTP_VERSION"])) {
            return $_SERVER["HTTP_VERSION"];
        }

        //app
        if (!empty($_REQUEST["version"])) {
            return $_REQUEST["version"];
        }
        //browser
        if (!empty($_REQUEST["platform"])) {
            return $_REQUEST["platform"];
        }

        return '';
    }

    /**
     * 获取IP
     * 
     * @return string
     */
    public function _getIp() {
        if (!empty($_REQUEST["ip"])) {
            return $_REQUEST["ip"];
        }
        return $_SERVER['REMOTE_ADDR'];
    }

    /**
     * 校验表单
     */
    protected function _validateForm($form) {
        if (!$form->validate()) {
            throw new \Exception(current($form->getMessages()), 110010);
        }
        return $form->getFieldValue();
    }

}
